package com.esdk.sql.orm;

import com.esdk.esdk;
import com.esdk.sql.*;
import com.esdk.utils.Constant;

import java.sql.Connection;

public class SelectFactory implements AutoCloseable{
	private final Connection conn;
  private boolean useSessionCache=false;

  public SelectFactory(Connection conn){
    this.conn=conn;
  }

	public SelectFactory(Connection conn,boolean useSessionCache){
		this.conn=conn;
    this.useSessionCache=useSessionCache;
	}
	
  public Connection getConnection() {
    return this.conn;
  }

  public Select createSelect(String tableName){
    return new Select(tableName,conn).useSessionCache(this.useSessionCache);
  }

  public Insert createInsert(String tableName){
    return new Insert(tableName,conn);
  }

  public Update createUpdate(String tableName){
    return new Update(tableName,conn);
  }

  public SmartPersistence createSave(String tableName){
    return new SmartPersistence(tableName,conn);
  }

  public Delete createDelete(String tableName){
    return new Delete(tableName,conn);
  }


  public <T extends AbstractSelect> T createSelect(Class<T> selectClass) throws Exception{
    return (T)esdk.reflect.safeNewInstance(selectClass,conn).useSessionCache(this.useSessionCache);
  }
  
  public <T extends ParentRow> T createRow(Class<T> parentRowClass) throws Exception{
    T row=(T)esdk.reflect.safeNewInstance(parentRowClass);
    row.setConnection(conn);
    row.useSessionCache(this.useSessionCache);
    return row;
  }
  
  public <T extends ParentRow> T createRow(Class<T> parentRowClass,Object pkid) throws Exception{
    return createRow(parentRowClass,pkid,false);
  }
  
  public <T extends ParentRow> T createRow(Class<T> parentRowClass,Object pkid,boolean useCache) throws Exception{
  	return createRow(parentRowClass,pkid,useCache?Constant.DefaultCacheSec:Constant.ResetUseCacheSec);
  }

  public <T extends ParentRow> T createRow(Class<T> parentRowClass,Object pkid,int cacheSec) throws Exception{
    T row=esdk.reflect.safeNewInstance(parentRowClass);
    row.setConnection(conn);
    row.useCache(cacheSec);
    row.setPrimaryKey(pkid);
    row.useSessionCache(this.useSessionCache);
    row.refresh();
    return row;
  }
	
  @Override
  public void close(){
    if(useSessionCache)
      ORMSessionFactory.removeORMSession(conn);
    esdk.sql.close(conn);
  }

  public SelectFactory useSessionCache(boolean useSessionCache){
    this.useSessionCache=useSessionCache;
    return this;
  }
}
